package com.atguigu.guli.service.edu.service.impl;

import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.edu.entity.Chapter;
import com.atguigu.guli.service.edu.entity.ChapterVo;
import com.atguigu.guli.service.edu.entity.Video;
import com.atguigu.guli.service.edu.entity.VideoVo;
import com.atguigu.guli.service.edu.mapper.ChapterMapper;
import com.atguigu.guli.service.edu.service.ChapterService;
import com.atguigu.guli.service.edu.service.VideoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-01-04
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;
    @Override
    public List<ChapterVo> getChapterVideoByCourseId(String courseId) {
       //查询章节
        LambdaQueryWrapper<Chapter> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Chapter::getCourseId,courseId);
        List<Chapter> chapters = baseMapper.selectList(queryWrapper);
      //查询小节
        LambdaQueryWrapper<Video> videoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        videoLambdaQueryWrapper.eq(Video::getCourseId,courseId);
        List<Video> videoList = videoService.list(videoLambdaQueryWrapper);

        List<ChapterVo> chapterVoList = new ArrayList<>();

        for (Chapter chapter : chapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            chapterVoList.add(chapterVo);

            //小节封装
            List<VideoVo> videoVoList = new ArrayList<>();
            for (Video video : videoList) {
                if (video.getChapterId() ==chapter.getId()){
                    VideoVo videoVo =new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                   videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }


        return chapterVoList;
    }

    @Override
    public void deleteChapter(String chapterId) {
        LambdaQueryWrapper<Video> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Video::getChapterId,chapterId);
        int count = videoService.count(lambdaQueryWrapper);
        if (count>0){
            throw  new GuliException(20001,"不能删除");
        }else {
            int i = baseMapper.deleteById(chapterId);
        }
    }
}
